'''
Created on 2009-11-11

@author: Jialai_Zhu
'''
##################################
#-*- coding:utf8 -*-             #
import urllib2
class ErrorHandler(urllib2.HTTPDefaultErrorHandler):
    def http_error_default(self, req, fp, code, msg, headers):
        result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
        result.status = code
        return result
from util import process

class gsb_server(object):
    '''
    classdocs
    '''
    def __del__(self):
        try:
            self.process.kill()
        except:
            pass    

    def __init__(self):
        '''
        Constructor
        '''        
        self.bootup()

    def bootup(self):
        try:
    #        cmd="c:\WINDOWS\system32\cmd.exe"
            pathexe=path.path(r'\gsb\server.exe')
            pathconf=path.path(r'\gsb\squid-gsb.conf')   
    #        arg1=pathexe.tostring();
    #        arg2='-c '
    #        arg3=pathconf.tostring(pathconf.fp());    
    #        
            args=[pathexe.fp(),'-c',pathconf.fp()]     
            #self.pid=os.execv(cmd,args )
    #        os.popen(arg1+' '+' ' +arg2+' '+arg3)
            self.process=process.run(args)
            return True
        except:
            return False    
        
        
        
    def check(self,url):        
        try:
            if self.process:
                return self.req(url)
        except:
            if self.bootup():
                return self.req(url)
            return False
                
    def req(self,url):    
        req=urllib2.Request("http://127.0.0.1:897/url="+url)
        mgr=urllib2.build_opener(ErrorHandler())    
        ns=mgr.open(req)
        return ns.code==404
    
from util import path
instance=gsb_server()    